//
//  TimerViewModel.swift
//  focusOn
//
//  Created by 恒 on 2025/7/3.
//

import SwiftUI
import AVFoundation
import Combine
import UIKit

class TimerViewModel: ObservableObject {
    private var audioPlayer: AVAudioPlayer?
    private var catEatPlayer: AVAudioPlayer?
    
    // 计时器状态
    @Published var timeRemaining = 60
    @Published var isTimerRunning = false
    @Published var cancelCountdown = 20
    @Published var isCanceling = false
    @Published var selectedMode: TimerMode = .custom {
        didSet {
            UserDefaults.standard.set(selectedMode.rawValue, forKey: "selectedMode")
        }
    }
    @Published var isWorkPhase = true
    @Published var defaultMinutes = 5 {
        didSet {
            if defaultMinutes < 5 {
                defaultMinutes = 5
            }
        }
    }
    @Published var showingModeSelection = false
    @Published var isAnimating = false
    @Published var initialTime = 0
    @Published var score = 0
    @Published var totalMinutes = 0
    @Published var showingMusicSettings = false
    @Published var availableMusics: [String] = [] // 动态加载音乐文件列表
    @Published var selectedMusic = "catEat" {
        didSet {
            UserDefaults.standard.set(selectedMusic, forKey: "selectedMusic")
            loadBackgroundMusic()
//            if playMusicOnLaunch {
//                audioPlayer?.play()
//            }
        }
    }
    /**
            
     */
    @Published var playMusicOnLaunch = true {
        didSet {
            UserDefaults.standard.set(playMusicOnLaunch, forKey: "playMusicOnLaunch")
        }
    }
    
    // 常量定义
    private let pomodoroWorkTime = 25 * 60
    private let pomodoroBreakTime = 5 * 60
    private var timer: AnyCancellable?
    private var cancelTimer: AnyCancellable?

    init() {
        loadAvailableMusics()
        loadBackgroundMusic()
        loadCatEatSound()
        loadSavedModes()
        // 加载选中的模式
        if let savedMode = UserDefaults.standard.string(forKey: "selectedMode") {
            selectedMode = TimerMode(rawValue: savedMode) ?? .custom
        }
        score = UserDefaults.standard.integer(forKey: "totalScore")
        totalMinutes = UserDefaults.standard.integer(forKey: "totalMinutes")
        // 打开页面不要播放音乐
        //selectedMusic = UserDefaults.standard.string(forKey: "selectedMusic") ?? "catEat"
        playMusicOnLaunch = UserDefaults.standard.bool(forKey: "playMusicOnLaunch")
        // 确保选中的音乐存在于可用列表中
        if let savedMusic = UserDefaults.standard.string(forKey: "selectedMusic"), availableMusics.contains(savedMusic) {
            selectedMusic = savedMusic
        } else if !availableMusics.isEmpty {
            selectedMusic = availableMusics.first!
            UserDefaults.standard.set(selectedMusic, forKey: "selectedMusic")
        }
    }
    
    // 重新加载可用音乐列表
    func reloadAvailableMusics() {
        loadAvailableMusics()
        // 确保选中的音乐仍然存在
        if !availableMusics.contains(selectedMusic) {
            if !availableMusics.isEmpty {
                selectedMusic = availableMusics.first!
                UserDefaults.standard.set(selectedMusic, forKey: "selectedMusic")
            } else {
                selectedMusic = ""
            }
        }
    }

    func loadBackgroundMusic() {
        guard let path = Bundle.main.path(forResource: selectedMusic, ofType: "m4a") else {
            print("背景音乐文件未找到")
            return
        }
        let url = URL(fileURLWithPath: path)
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.numberOfLoops = -1 // 循环播放
            audioPlayer?.prepareToPlay()
        } catch {
            print("音频加载失败: \(error.localizedDescription)")
        }
    }
    
    // 动态加载所有可用音乐文件
    private func loadAvailableMusics() {
        guard let resourcePath = Bundle.main.resourcePath else { return }
        do {
            let files = try FileManager.default.contentsOfDirectory(atPath: resourcePath)
            availableMusics = files.filter { $0.hasSuffix(".m4a") }
                .map { URL(fileURLWithPath: $0).deletingPathExtension().lastPathComponent }
        } catch {
            print("加载音乐文件失败: \(error.localizedDescription)")
        }
    }

    func loadCatEatSound() {
        guard let path = Bundle.main.path(forResource: "catEat", ofType: "m4a") else {
            print("catEat音频文件未找到")
            return
        }
        let url = URL(fileURLWithPath: path)
        do {
            catEatPlayer = try AVAudioPlayer(contentsOf: url)
            catEatPlayer?.prepareToPlay()
        } catch {
            print("catEat音频加载失败: \(error.localizedDescription)")
        }
    }
    
    
    // 格式化时间显示
    func timeString(time: Int) -> String {
        let minutes = time / 60
        let seconds = time % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
    
    // 切换计时器状态
    func toggleTimer() {
        if isTimerRunning {
            confirmStop()
        } else {
            startTimer()
        }
    }
    
    // 保存的模式列表
    @Published var savedModes: [Int] = [] {
        didSet {
            UserDefaults.standard.set(savedModes, forKey: "savedModes")
        }
    }
    
    // 保存自定义模式
    func saveCustomMode() {
        // 检查是否已存在相同的模式
        if !savedModes.contains(defaultMinutes) {
            savedModes.append(defaultMinutes)
            // 排序模式列表
            savedModes.sort()
        }
        
        // 显示保存成功的提示
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(.success)
    }
    
    // 加载保存的模式
    func loadSavedModes() {
        if let modes = UserDefaults.standard.array(forKey: "savedModes") as? [Int] {
            savedModes = modes
        }
    }
    
    // 删除模式
    func deleteMode(_ mode: Int) {
        if let index = savedModes.firstIndex(of: mode) {
            savedModes.remove(at: index)
            // 显示删除成功的提示
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.success)
        }
    }
    
    // 开始计时器
    func startTimer() {
        isAnimating = true
        // 确保audioPlayer已初始化
        if audioPlayer == nil {
            loadBackgroundMusic()
        }
        // 只有在playMusicOnLaunch为true时才播放音乐
        if playMusicOnLaunch {
            audioPlayer?.play()
        }
        if selectedMode == .pomodoro {
            timeRemaining = isWorkPhase ? pomodoroWorkTime : pomodoroBreakTime
        } else {
            timeRemaining = defaultMinutes * 60
        }
        
        initialTime = timeRemaining
        
        // 震动反馈
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(.success)
        
        timer?.cancel()
        self.isAnimating = false
        print("start timer: \(timeRemaining)")
        SharedDataStore.solidTimeSecond = Double(timeRemaining)
        timer = Timer.publish(every: 1, on: .main, in: .common)
            .autoconnect()
            .sink {_ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                    print("日期改变了：\(self.timeRemaining)")
                    SharedDataStore.sharedDouble = Double(self.timeRemaining)
                } else {
                    if self.selectedMode == .pomodoro {
                        self.isWorkPhase.toggle()
                        // 工作阶段完成时加分
                        if !self.isWorkPhase {
                            self.addScore()
                            self.addMinutes(self.pomodoroWorkTime / 60)
                        }
                        self.timeRemaining = self.isWorkPhase ? self.pomodoroWorkTime : self.pomodoroBreakTime
                        self.initialTime = self.timeRemaining
                        let generator = UINotificationFeedbackGenerator()
                        generator.notificationOccurred(.success)
                    } else {
                        self.audioPlayer?.stop()
                        self.confirmStop(feedbackType: .success)
                        self.addScore()
                        self.addMinutes(self.defaultMinutes)
                    }
                }
            }
        
        startCancelCountdown()
        isTimerRunning = true
    }
    
    // 开始取消倒计时
    private func startCancelCountdown() {
        isCanceling = true
        cancelCountdown = 20
        
        cancelTimer?.cancel()
        cancelTimer = Timer.publish(every: 1, on: .main, in: .common)
            .autoconnect()
            .sink {_ in
                if self.cancelCountdown > 0 {
                    self.cancelCountdown -= 1
                } else {
                    self.isCanceling = false
                    self.cancelTimer?.cancel()
                }
            }
    }
    
    // 确认停止计时器
    func confirmStop(feedbackType: UINotificationFeedbackGenerator.FeedbackType = .warning) {
        audioPlayer?.stop()
        catEatPlayer?.stop()
        
        timer?.cancel()
        cancelTimer?.cancel()
        
        // 检查是否在取消倒计时内
        let wasCanceling = isCanceling
        
        isTimerRunning = false
        isCanceling = false
        timeRemaining = 0
        SharedDataStore.sharedDouble = 0
        
        // 如果超过20秒停止，扣分
        if !wasCanceling {
            subtractScore()
        }
        
        // 震动反馈
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(feedbackType)
    }
    
    private func addScore() {
        score += 1
        UserDefaults.standard.set(score, forKey: "totalScore")
    }
    
    private func subtractScore() {
        if score > 0 {
            score -= 1
            UserDefaults.standard.set(score, forKey: "totalScore")
        }
    }
    
    private func addMinutes(_ minutes: Int) {
        totalMinutes += minutes
        UserDefaults.standard.set(totalMinutes, forKey: "totalMinutes")
    }
    
}
